package com.tezign.intelligence.mini.dam.aifamilyconsultant.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.dashscope.common.Role;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.google.common.collect.Lists;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.ResponseBean;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.UserStatusEnum;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.CreateUserSession;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.req.UpdateUserSession;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.bean.resp.UserSessionResp;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.entity.*;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.FamilyStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.interceptor.UserStore;
import com.tezign.intelligence.mini.dam.aifamilyconsultant.service.*;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.stream.Collectors;

import static com.tezign.intelligence.mini.dam.aifamilyconsultant.constant.Constant.SESSION_PROMPT_SUFFIX;
import static com.tezign.intelligence.mini.dam.aifamilyconsultant.controller.AdminController.SESSION_PROMPT_KEY;

/**
 * <p>
 * 用户会话信息 前端控制器
 * </p>
 *
 * @author six
 * @since 2024-11-16
 */
@Api(tags = "用户会话管理")
@Slf4j
@CrossOrigin("*")
@RestController
@RequiredArgsConstructor
@RequestMapping(Constant.APPLICATION_NAME + "/userSession")
public class UserSessionController {
	private final IUserSessionService userSessionService;
	private final ISessionService sessionService;
	private final IUserService userService;
	private final IFamilyService familyService;
	private final IFamilyMemberService familyMemberService;

	private final RedisTemplate<String, String> redisTemplate;

	// 获取用户会话信息 列表
	@GetMapping("/list")
	@ApiOperation(value = "获取用户会话信息列表")
	public ResponseBean<List<UserSessionResp>> list() {
		Long userId = UserStore.getUserId();
		Long familyId = FamilyStore.getFamilyId();
		Family family = familyService.getById(familyId);
		if (family == null) {
			return new ResponseBean<List<UserSessionResp>>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		log.info("获取用户会话信息列表, userId: {}, familyId: {}", userId, familyId);
		List<UserSession> sessions = userSessionService.lambdaQuery().eq(UserSession::getUserId, userId).eq(UserSession::getFamilyId, familyId).orderByDesc(UserSession::getId).last("limit 20").list();
		return new ResponseBean<List<UserSessionResp>>().success(sessions.stream().map(x -> BeanUtil.copyProperties(x, UserSessionResp.class)).collect(Collectors.toList()));
	}

	// 创建用户会话信息
	@PostMapping("/create")
	@ApiOperation(value = "创建用户会话信息")
	public ResponseBean<UserSessionResp> create(@RequestBody CreateUserSession createReq) {
		Long userId = UserStore.getUserId();
		Long familyId = FamilyStore.getFamilyId();
		log.info("创建用户会话信息, userId: {}, familyId: {} createReq:{}", userId, familyId, JSONUtil.toJsonStr(createReq));
		Family family = familyService.getById(familyId);
		if (family == null) {
			return new ResponseBean<UserSessionResp>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}

		UserSession session = new UserSession();
		session.setUserId(userId);
		session.setFamilyId(familyId);
		session.setName("默认话题");
		userSessionService.save(session);

		Session se = new Session();
		se.setUserSessionId(session.getId());
		se.setRole(Role.SYSTEM.getValue());
		String prompt = redisTemplate.opsForValue().get(SESSION_PROMPT_KEY);

		User userInfo = userService.getById(userId);
		FamilyMember familyMember = familyMemberService.lambdaQuery().eq(FamilyMember::getUserId, userId).one();
		prompt += String.format(SESSION_PROMPT_SUFFIX, userInfo.getName(), familyMember.getRole());

		se.setContent(StringUtils.isEmpty(prompt) ? createReq.getContent() : prompt);

		// 由于有预置问题，无需再开启默认回复
//		Session se2 = new Session();
//		se2.setUserSessionId(session.getId());
//		se2.setRole(Role.ASSISTANT.getValue());
//		se2.setContent("哈喽，你好啊，今天我们聊些什么呢？");

		sessionService.saveBatch(Lists.newArrayList(se));

		family.setSessionCount(family.getSessionCount() + 1);
		familyService.updateById(family);


		return new ResponseBean<UserSessionResp>().success(BeanUtil.copyProperties(session, UserSessionResp.class));
	}

	// 修改用户会话信息
	@PostMapping("/update")
	@ApiOperation(value = "修改用户会话信息")
	public ResponseBean<UserSessionResp> update(@RequestBody UpdateUserSession updateReq) {
		Long userId = UserStore.getUserId();
		Long familyId = FamilyStore.getFamilyId();
		log.info("修改用户会话信息, userId: {}, familyId: {} updateReq:{}", userId, familyId, JSONUtil.toJsonStr(updateReq));
		Family family = familyService.getById(familyId);
		if (family == null) {
			return new ResponseBean<UserSessionResp>().exception(UserStatusEnum.ERROR.addErrorMsg("家庭不存在"));
		}
		UserSession session = userSessionService.lambdaQuery().eq(UserSession::getUserId, userId).eq(UserSession::getFamilyId, familyId).eq(UserSession::getId, updateReq.getId()).one();
		if (session == null) {
			return new ResponseBean<UserSessionResp>().exception(UserStatusEnum.ERROR.addErrorMsg("会话不存在"));
		}
		session.setName(updateReq.getName());
		userSessionService.updateById(session);
		return new ResponseBean<UserSessionResp>().success(BeanUtil.copyProperties(session, UserSessionResp.class));
	}
}
